import axios from 'axios'
import {Toast} from 'vant'
import i18n from "@/locale/index";
import router from "@/router";

const {tm} = i18n.global
const baseUrl = process.env.NODE_ENV === 'development' ? '/api' : window.origin + '/admin-domain/api/'
// 创建axios实例
const service = axios.create({
    timeout: 1000 * 60, // 请求超时时间ss
    baseURL: baseUrl
})
const codeMessage = {
    404: tm('server_unconnect'),
    1000: tm('connect_time_out'),
};
// request拦截器
service.interceptors.request.use(config => {
    const token = localStorage.getItem('token')
    const userId = localStorage.getItem('userId')
    const locale = localStorage.getItem('locale')
    if (token) {
        config.headers.token = token
    }
    if (userId){
        config.headers.userId = userId
    }
    if (locale){
        config.headers.language = locale
    }
    return config
}, error => {
    Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(
    response => {
        const {code, message} = response.data
        const codeSuccess = [1, 10]
        if (codeSuccess.indexOf(code) === -1) {
            Toast({
                message: message
            })
            if (code === 100) {
                router.push('/login')
            }
        }
        return response.data
    },
    error => {
        let code
        try {
            code = error.response.status
        } catch {
            //请求超时
            if (error.code === 'ECONNABORTED') {
                code = 1000
            }
        }
        Toast({
            message: codeMessage[code] ? code + " " + codeMessage[code] : error,
        })
        return Promise.reject()
    }
)

export default service
